package info.wangyuan.agent.controller.admin;

import info.wangyuan.agent.entity.po.KnowledgeBase;
import info.wangyuan.agent.exception.BusinessException;
import info.wangyuan.agent.service.curd.KnowledgeBaseService;
import info.wangyuan.agent.utils.Result;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;
import java.util.List;

/**
 * 知识库管理
 *
 * @author Albert
 * @since 2025-07-15 21:52:35
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/admin/knowledgeBase")
public class KnowledgeBaseController {

    private final KnowledgeBaseService knowledgeBaseService;

    public KnowledgeBaseController(KnowledgeBaseService knowledgeBaseService) {
        this.knowledgeBaseService = knowledgeBaseService;
    }

    /**
     * 获取知识库列表
     */
    @GetMapping("/list")
    public Result<List<KnowledgeBase>> getKnowledgeBaseList() {
        return Result.success(knowledgeBaseService.list());
    }

    /**
     * 添加知识库
     */
    @PostMapping("/add")
    public Result<Void> addKnowledgeBase(@RequestBody @Valid KnowledgeBase knowledgeBase) {
        knowledgeBaseService.canAdd(knowledgeBase);
        return Result.success();
    }

    /**
     * 知识库修改
     */
    @PostMapping("/update")
    public Result<Void> updateKnowledgeBase(@RequestBody @Valid KnowledgeBase knowledgeBase) {
        knowledgeBaseService.canUpdate(knowledgeBase);
        return Result.success();
    }

    /**
     * 知识库删除
     */
    @DeleteMapping("/delete/{id}")
    public Result<Void> deleteKnowledgeBase(@PathVariable @NotNull Integer id) {
        knowledgeBaseService.canDelete(id);
        return Result.success();
    }

    /**
     * 知识库文件导出 -> zip
     */
    @GetMapping("/download/{id}")
    public Result<ResponseEntity<StreamingResponseBody>> outputKnowledgeBase(@PathVariable @NotNull Integer id) {
        try {
            return Result.success(knowledgeBaseService.downloadFolderZip(id));
        } catch (IOException e) {
            throw new BusinessException("知识库文件导出失败", e);
        }
    }

}
